package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//将当前自定义的realm交给Spring容器管理
@Component("crmRealm")
public class CRMRealm extends AuthorizingRealm{
    @Autowired
    private EmployeeMapper mapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    //获取认证信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        //根据用户的账号去数据库查询用户信息employee
        Employee employee = mapper.selectByUsername(username);
        if (employee != null){
            //身份类似于我们保存在session作用域中的账号
            //凭证
            return new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getName()),"crmRealm");
        }
        return null;
    }


    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) throws AuthorizationException{
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //获取当前登录的用户
        Employee currentEmp = (Employee)principalCollection.getPrimaryPrincipal();
        //如果是超管,给所有的权限和admin的角色
        if (currentEmp.isAdmin()){
            info.addRole("admin");
            info.addStringPermission("*:*");
        }else {
            //如果不是超管,根据当前用户的id去数据库中查询对应的角色和权限表达式(Expressions)
            List<String> roleSns = roleMapper.selectRoleSnsByEmpId(currentEmp.getId());
            List<String> expressions = permissionMapper.queryByEmployeeId(currentEmp.getId());
            //为当前通过认证的用户授权
            info.addRoles(roleSns);
            info.addStringPermissions(expressions);
        }

        return info;
    }
}


































